import { View } from '@tarojs/components';
import { Popup, Input, Button } from '@nutui/nutui-react-taro';
import { IVoice } from '../..';
import VoiceCard from './voice-card';
import { useState } from 'react';
import Taro from '@tarojs/taro';
import { uploadFileByForm } from '@/tools/upload';
import { getUser } from '@/utils/user';
import './index.less';

interface IProps {
  onRefresh: () => void;
  voiceList: IVoice[];
}

export default function Index(props: IProps) {
  const { voiceList = [] } = props || {};
  const [showUploadPopup, setShowUploadPopup] = useState(false);
  const [voiceName, setVoiceName] = useState('');
  const [voiceFile, setVoiceFile] = useState<any>(null);
  const [uploading, setUploading] = useState(false);

  const handleUploadClick = () => {
    setShowUploadPopup(true);
  };

  // 处理选择音频
  const handleSelectVoice = async () => {
    try {
      const res = await Taro.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['mp3', 'wav', 'm4a'],
      });

      if (res.tempFiles[0]) {
        setVoiceFile(res.tempFiles[0].path);
      }
    } catch (error) {
      console.error('选择音频失败:', error);
      Taro.showToast({
        title: '选择音频失败',
        icon: 'none',
      });
    }
  };

  // 处理上传
  const handleSubmit = async () => {
    if (!voiceFile) {
      Taro.showToast({
        title: '请选择音频文件',
        icon: 'none',
      });
      return;
    }

    if (!voiceName.trim()) {
      Taro.showToast({
        title: '请输入音频名称',
        icon: 'none',
      });
      return;
    }

    setUploading(true);
    try {
      // 获取用户ID
      const userId = getUser().id;

      // 上传音频文件
      const uploadRes = await uploadFileByForm('/voice/upload', voiceFile, {
        userId,
        name: voiceName,
      });

      if (uploadRes.code === 200) {
        Taro.showToast({
          title: '上传成功',
          icon: 'success',
        });
        setShowUploadPopup(false);
        setVoiceName('');
        setVoiceFile(null);
        // TODO: 刷新音频列表
        props.onRefresh();
      } else {
        throw new Error(uploadRes.data?.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      Taro.showToast({
        title: error.message || '上传失败',
        icon: 'none',
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <View className="dou-voice">
      <View className="voice-list">
        <View className="voice-item upload" onClick={handleUploadClick}>
          <View className="upload-icon">+</View>
          <View className="upload-text">上传声音</View>
        </View>

        {voiceList.map((item, index) => (
          <VoiceCard key={index} voice={item} />
        ))}
        <View className="title">
          <View className="icon" />
          使用说明
        </View>
        <View className="content primary">1. 上传一段7-20秒的音频</View>
        <View className="content primary">
          2. 注意：音频中不要重复只念一两个字
        </View>
        <View className="content primary">
          3.
          如果你不知道要说什么，可以试着念一下：“你今天的穿搭和平时很不一样，特别像一个明星。很适合你，以后要多走这种风格呀”
        </View>
        <View className="content primary">4. 注意：不要上传超过30秒的音频</View>
        <View className="content primary">
          5. 注意：克隆音频会消耗100cc，请确保额度充足
        </View>
      </View>

      <Popup
        visible={showUploadPopup}
        onClose={() => {
          setShowUploadPopup(false);
          setVoiceName('');
          setVoiceFile(null);
        }}
        position="bottom"
        round>
        <View className="upload-popup">
          <View className="popup-title">上传音频</View>
          <View className="upload-form">
            <View className="form-item">
              <Input
                className="voice-name-input"
                placeholder="请输入音频名称"
                value={voiceName}
                onChange={(val) => setVoiceName(val)}
              />
            </View>
            <View className="form-item">
              <Button className="select-voice-btn" onClick={handleSelectVoice}>
                {voiceFile ? '重新选择音频' : '选择音频'}
              </Button>
            </View>
            <View className="form-item">
              <Button
                className="submit-btn"
                type="primary"
                loading={uploading}
                onClick={handleSubmit}>
                上传
              </Button>
            </View>
          </View>
        </View>
      </Popup>
    </View>
  );
}
